﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObTookit.HighLight
{
    public class LineNumber
    {
        public void ShowLineNo(System.Windows.Forms.RichTextBox rtb, System.Windows.Forms.Panel pnl)
        {
            //获得当前坐标信息

            Point p = new Point(0, 0); ;
            int crntFirstIndex = rtb.GetCharIndexFromPosition(p);

            int crntFirstLine = rtb.GetLineFromCharIndex(crntFirstIndex);

            Point crntFirstPos = rtb.GetPositionFromCharIndex(crntFirstIndex);

            //
            p.Y += rtb.Height;

            //

            int crntLastIndex = rtb.GetCharIndexFromPosition(p);

            int crntLastLine = rtb.GetLineFromCharIndex(crntLastIndex);
            Point crntLastPos = rtb.GetPositionFromCharIndex(crntLastIndex);

            //

            //

            //准备画图
            Graphics g = pnl.CreateGraphics();

            Font font = new Font(rtb.Font, rtb.Font.Style);

            SolidBrush brush = new SolidBrush(Color.Green);

            //
            //

            //画图开始

            //刷新画布

            Rectangle rect = pnl.ClientRectangle;
            brush.Color = pnl.BackColor;

            g.FillRectangle(brush, 0, 0, pnl.ClientRectangle.Width, pnl.ClientRectangle.Height);

            brush.Color = Color.Green;//重置画笔颜色

            //
            //绘制行号

            int lineSpace = 0;

            if (crntFirstLine != crntLastLine)
            {
                lineSpace = (crntLastPos.Y - crntFirstPos.Y) / (crntLastLine - crntFirstLine);

            }

            else
            {
                lineSpace = Convert.ToInt32(rtb.Font.Size);

            }

            int brushX = pnl.ClientRectangle.Width - Convert.ToInt32(font.Size * 3);

            int brushY = crntLastPos.Y + Convert.ToInt32(font.Size * 0.21f);//惊人的算法啊！！
            for (int i = crntLastLine; i >= crntFirstLine; i--)
            {

                g.DrawString((i + 1).ToString(), font, brush, brushX, brushY);

                brushY -= lineSpace;
            }

            g.Dispose();

            font.Dispose();

            brush.Dispose();
        }
    }
}
